package com.jianyun.jyzs.adapter;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.activity.SelectContact2Activity;
import com.jianyun.jyzs.bean.ContactCheckType;
import com.jianyun.jyzs.bean.ListItemModel;
import com.jianyun.jyzs.bean.SelectedContactInfo;
import com.jianyun.jyzs.bean.User;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.rongcloud.rce.lib.utils.DefaultPortraitGenerate;


/**
 * Created by yangshijun on 2018/7/17.
 * 工程动态---》选择联系人
 */

public class SelectPersonAdpater extends RecyclerView.Adapter implements Handler.Callback {


    private final SelectContact2Activity context;
    private final ContactModel contactModel;
    private List<User> list;
    private ItemClickListener itemClickListener;
    protected ContactItemClickListener contactItemClickListener;
    protected FriendItemClickListener friendItemClickListener;
    private int maxSelectCount = Integer.MAX_VALUE;
    private List<ListItemModel> curItemModels;
    private List<ListItemModel> rootItemModels;
    private String userId;

    public SelectPersonAdpater(SelectContact2Activity activity, List<User> list,String userId) {
        rootItemModels = new ArrayList<>();
        this.context = activity;
        this.list = list;
        curItemModels = rootItemModels;
        contactModel = new ContactModel();
        this.userId=userId;
    }

    public void setList(List<User> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.rce_check_contact_item_2, null);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        SelectPersonAdpater.MyHolder myHolder = (MyHolder) holder;
        User user = list.get(position);
        LinkedHashMap<String, SelectedContactInfo> selectedContactInfoList = context.selectedContactInfoList;
        ContactModel contactModel = new ContactModel();
        SelectedContactInfo selectedContactInfo = selectedContactInfoList.get(user.getServerUserId());
        if (selectedContactInfo!=null){
            if (selectedContactInfo.getId().equals(userId)){
                contactModel.checkType=ContactCheckType.CHECKED_GRAY;
            }else {
                contactModel.checkType=ContactCheckType.CHECKED;
            }

        }else {
            contactModel.checkType=ContactCheckType.NONE;
        }

        contactModel.setId(user.getServerUserId());
        contactModel.name = user.getNameZh();
        contactModel.departName = user.getDepartment();
        contactModel.path = user.getLocalIconPath();
        contactModel.portrait = user.getServerIconPath();
        contactModel.phoneNumber = user.getPhoneNum();
        myHolder.updateContactItem(contactModel);


    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public void setMaxSelectCount(int maxSelectCount) {
        this.maxSelectCount = maxSelectCount;
    }


    class MyHolder extends RecyclerView.ViewHolder {

        private ImageView portraitImageView;
        private ImageView checkBox;
        private TextView titleTextView;
        private ImageView deleteImageView;

        public MyHolder(View itemView) {
            super(itemView);
            portraitImageView = (ImageView) itemView.findViewById(R.id.rce_portrait);
            checkBox = (ImageView) itemView.findViewById(R.id.rce_checkbox);
            titleTextView = (TextView) itemView.findViewById(R.id.rce_title);
            deleteImageView = (ImageView) itemView.findViewById(R.id.rce_delete);
        }


        private void updateContactItem(final ContactModel contactModel) {
            checkBox.setVisibility(View.VISIBLE);
            checkBox.setClickable(false);
            if (contactModel.checkType == ContactCheckType.CHECKED_GRAY) {
                itemView.setEnabled(false);
                checkBox.setImageResource(R.drawable.rce_ic_checkbox_full_gray);
            } else {
                itemView.setEnabled(true);
                checkBox.setImageResource(contactModel.checkType == ContactCheckType.CHECKED ? R.drawable.rce_ic_checkbox_full : R.drawable.rce_ic_checkbox_none);
            }
            portraitImageView.setVisibility(View.VISIBLE);
            titleTextView.setVisibility(View.VISIBLE);
            deleteImageView.setVisibility(View.GONE);
            String portrait = contactModel.portrait;
            if (TextUtils.isEmpty(portrait)) {
                //  portrait = DefaultPortraitGenerate.generateDefaultAvatar(contactModel.name, contactModel.getId());
            }
            //portraitImageView.setAvatar(Uri.parse(portrait));
            titleTextView.setText(contactModel.name);
            deleteImageView.setVisibility(View.INVISIBLE);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (contactModel.checkType == ContactCheckType.NONE && SelectContact2Activity.getSelectedList().size() + 1 > maxSelectCount) {
                        context.exceedMaxSelectCount();
                        return;
                    }
                    contactModel.checkType = contactModel.checkType == ContactCheckType.NONE ? ContactCheckType.CHECKED : ContactCheckType.NONE;
                    checkBox.setImageResource(contactModel.checkType == ContactCheckType.CHECKED ? R.drawable.rce_ic_checkbox_full : R.drawable.rce_ic_checkbox_none);
                    SelectedContactInfo contactInfo = new SelectedContactInfo();
                    contactInfo.setId(contactModel.id);
                    contactInfo.setName(contactModel.name);
                    contactInfo.setPortraitUrl(contactModel.portrait);
                    contactInfo.setDepartPath(contactModel.path);
                    contactInfo.setDepartName(contactModel.departName);
                    contactInfo.setPhoneNumber(contactModel.phoneNumber);
                    itemClickListener.onContactChecked(contactInfo, contactModel.checkType == ContactCheckType.CHECKED);
                }
            });
        }
    }

    public boolean isSelectedAll() {
        boolean selectedAll = false;
        for (ListItemModel model : curItemModels) {
//            if (model instanceof ContactModel) {
//                selectedAll = ((ContactModel) model).checkType != ContactCheckType.NONE;
//                if (!selectedAll) break;
//            } else if (model instanceof SelectContactAdapter.DepartmentModel) {
//                DepartmentModel departmentModel = (DepartmentModel) model;
//                selectedAll = departmentModel.checkType == DepartmentCheckType.FULL || departmentModel.checkType == DepartmentCheckType.FULL_GRAY;
//                if (!selectedAll) break;
//            }
        }
        return selectedAll;
    }

    /**
     * 检查当前显示 item 是否都可以点击，来决定全选 item 的点击行为。
     *
     * @return
     */
    public boolean isClickable() {
        boolean clickable = true;
//        for (ListItemModel model : curItemModels) {
//            if (model instanceof ContactModel) {
//                ContactModel contactModel = (ContactModel) model;
//                clickable = contactModel.checkType != ContactCheckType.CHECKED_GRAY;
//                if (clickable) break;
//            } else if (model instanceof SelectContactAdapter.DepartmentModel) {
//                DepartmentModel departmentModel = (DepartmentModel) model;
//                clickable = departmentModel.checkType != DepartmentCheckType.FULL_GRAY;
//                if (clickable) break;
//            }
//        }
        return clickable;
    }

    private static class ContactModel extends ListItemModel {
        ContactCheckType checkType = ContactCheckType.NONE;
        String name;
        String portrait;
        String path;
        String departName;
        String phoneNumber;

        ContactModel() {
            setType(R.layout.rce_check_contact_item_2);
        }

        String getName() {
            return name;
        }

        String getPortrait() {
            return portrait;
        }
    }


    public void addItemClickListener(ItemClickListener listener) {
        itemClickListener = listener;
    }

    public interface ItemClickListener {
        void onEnterDepartment(Map<String, String> path);

        void onContactChecked(SelectedContactInfo contactInfo, boolean checked);
    }

    private interface OperationCallback {
        void onSuccess(List<ListItemModel> itemModels);

        void onFail();
    }

    public interface ContactItemClickListener {
        void onClick(View v);
    }

    public void setOnContactItemClickListener(ContactItemClickListener listener) {
        contactItemClickListener = listener;
    }

    public interface FriendItemClickListener {
        void onClick(View v);
    }

    public void setOnFriendItemClickListener(FriendItemClickListener listener) {
        friendItemClickListener = listener;
    }
}
